package com.jdy.haoduoai.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.enums.SelectionMode;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.AlbumItem;
import com.jdy.haoduoai.model.DownloadItem;
import com.jdy.haoduoai.model.DownloadProgress;
import com.jdy.haoduoai.model.DownloadStateModel;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.task.BaseViewHolder;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.widget.AutoListView;
import com.jdy.haoduoai.widget.AutoListView.OnLoadListener;
import com.jdy.haoduoai.widget.AutoListView.OnRefreshListener;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@SuppressLint({"SimpleDateFormat", "ValidFragment"})
public class CompleteDownloadFragment extends BaseFragment implements
        OnRefreshListener, OnLoadListener, OnDataReceivedListener {

  @InjectView(id = R.id.listview_download)
  private AutoListView mCompletedListView;
  @InjectView(id = R.id.emptyview)
  private ImageView emptyview;

  private int mLastPage = 1;
  private boolean mCompletedDownloaded = true;
  private int mStoryType = 0;
  public int OP_TYPE = AutoListView.REFRESH;

  // private LeUser mLeUser;
  private List<DownloadItem> mEpisodeList = new ArrayList<DownloadItem>();
  public CompletedDownloadAdapter mCompletedDownloadAdapter;
  private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

  // private int mDownloadResId;
  public final float[] BT_SELECTED = new float[] { 1, 0, 0, 0, -50, 0, 1, 0, 0,
      -50, 0, 0, 1, 0, -50, 0, 0, 0, 1, 0 };

  private BaseActivity mActivity;

  // private CompleteDownloadFragment instance;

  public CompleteDownloadFragment(BaseActivity ba) {
    mActivity = ba;

  }

  @Override
  public View onCreateView(Bundle savedInstanceState, LayoutInflater inflater,
      ViewGroup container) {
    View bodyView = LayoutInflater.from(mContext).inflate(
        R.layout.complete_download_layout, container, false);

    mCompletedListView = (AutoListView) bodyView
        .findViewById(R.id.listview_download);

    mCompletedListView.setOnRefreshListener(this);
    mCompletedListView.setOnLoadListener(this);

    // IM init
    LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
//    mImHelper = LeXiaoXiaoBanApp.getInstance().getImHelper();
    SocketThreadManager.getInstance().setDataReceivedListener(this);
//    JSONObject jsonObject = new JSONObject();
//    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
//    try {
//      jsonObject.put("code", 202);
//      jsonObject.put("act", "connect");
//      jsonObject.put("data", lu.id);
//      SocketThreadManager.getInstance().send(jsonObject.toString());
//    } catch (JSONException e) {
//      e.printStackTrace();
//    }
  //  mImHelper.connect(lb.id);

    return bodyView;
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (mActivity != null && !mActivity.isFinishing()) {
      mActivity.showloading("");
    }

    init();
    fillList(null);
  }

  private void bindService() {

    if (mCompletedDownloaded && mStoryType == 0) {
      handleDownloadAccordType(AutoListView.REFRESH);
    }
  }

  private void init() {
    // instance = this;

    // mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    mCompletedDownloaded = getArguments().getBoolean("msg");
    mStoryType = getArguments().getInt("StoryType");

    bindService();

    mCompletedDownloadAdapter = new CompletedDownloadAdapter(getActivity(),
        R.layout.listitem_download, mEpisodeList);

    mCompletedListView.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int position,
          long arg3) {
        int pos = position - 1;
        if (pos >= 0) {
          if (mCompletedDownloadAdapter != null
              && !mCompletedDownloadAdapter.CheckBoxVisible) {
            List<DownloadItem> listItem = mCompletedDownloadAdapter.mDownloadedEpisodeList;
            if (mCompletedDownloaded && listItem != null) {
              DownloadItem di = listItem.get(pos);
              if (mStoryType == 0) {
                playvideo(di.id, "cartoon");
              } else {
                playvideo(di.id, "radio");
              }
            }
          }
        }
      }
    });
  }

  private void handleDownloadAccordType(final int what) {
    OP_TYPE = what;
    if (SocketThreadManager.getInstance() == null) {
      if (OP_TYPE == AutoListView.REFRESH) {
        mCompletedListView.onRefreshComplete();
      } else {
        mCompletedListView.onLoadComplete();
      }
      return;
    }

    if (OP_TYPE == AutoListView.REFRESH) {
      mLastPage = 1;
    } else {
      mLastPage++;
    }

    if (mCompletedDownloaded) {
      if (mStoryType == 0) {

      //  if (mImHelper != null && mImHelper.isLogin()) {
          try {
            JSONObject dataJson = new JSONObject();
            dataJson.put("code", 202);
            dataJson.put("act", "ctldownload");

            JSONObject dataJson22 = new JSONObject();
            dataJson22.put("op", "getdownloadlist");
            dataJson22.put("downloadstate", "finish");
            dataJson22.put("attribute", "cartoon");
            dataJson22.put("page", mLastPage);

            dataJson.put("data", dataJson22);
            SocketThreadManager.getInstance().send(dataJson.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
      //  }

      } else {

     //   if (mImHelper != null && mImHelper.isLogin()) {
          try {
            JSONObject dataJson = new JSONObject();
            dataJson.put("code", 202);
            dataJson.put("act", "ctldownload");

            JSONObject dataJson22 = new JSONObject();
            dataJson22.put("op", "getdownloadlist");
            dataJson22.put("downloadstate", "finish");
            dataJson22.put("attribute", "radio");
            dataJson22.put("page", mLastPage);

            dataJson.put("data", dataJson22);
            SocketThreadManager.getInstance().send(dataJson.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
       // }
      }
    } else {
      if (mStoryType == 0) {

      //  if (mImHelper != null && mImHelper.isLogin()) {
          try {
            JSONObject dataJson = new JSONObject();
            dataJson.put("code", 202);
            dataJson.put("act", "ctldownload");

            JSONObject dataJson22 = new JSONObject();
            dataJson22.put("op", "getdownloadlist");
            dataJson22.put("downloadstate", "downloading");
            dataJson22.put("attribute", "cartoon");
            dataJson22.put("page", mLastPage);

            dataJson.put("data", dataJson22);
            SocketThreadManager.getInstance().send(dataJson.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
      //  }
      } else {

     //   if (mImHelper != null && mImHelper.isLogin()) {
          try {
            JSONObject dataJson = new JSONObject();
            dataJson.put("code", 202);
            dataJson.put("act", "ctldownload");

            JSONObject dataJson22 = new JSONObject();
            dataJson22.put("op", "getdownloadlist");
            dataJson22.put("downloadstate", "downloading");
            dataJson22.put("attribute", "radio");
            dataJson22.put("page", mLastPage);

            dataJson.put("data", dataJson22);
            SocketThreadManager.getInstance().send(dataJson.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
     //   }
      }
    }
  }

  private void playvideo(final int sid, final String status) {
    new CustomAsyncTask(getActivity(), new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          DateUtils.showToast(getActivity(), "已推送到设备播放");
//          if (LeConfig.isDeviceConnect) {
//            DateUtils.showToast(getActivity(), "已推送到设备播放");
//          } else {
//            DateUtils.showToast(getActivity(), "未连接到设备，请检查设备联网情况！");
//          }

        } else {
          LeConfig.isDeviceConnect = false;
          DateUtils.showToast(getActivity(), "设备不在线");
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "cartoon");
        param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
       // param_.put("mode", "im");

        param_.put("reference", "push");
        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  public void setCompletedFlagValue(boolean complete) {
    this.mCompletedDownloaded = complete;
  }

  public void setStoryTypeValue(int type) {
    this.mStoryType = type;
  }

  public void updateCompletedFlagTrigger(boolean complete) {
    this.mCompletedDownloaded = complete;
    mEpisodeList.clear();
    handleDownloadAccordType(AutoListView.REFRESH);
  }

  public void updateStoryTypeFlagTrigger(int type) {
    this.mStoryType = type;
    mEpisodeList.clear();
    handleDownloadAccordType(AutoListView.REFRESH);
  }

  public class CompletedDownloadAdapter extends ArrayAdapter<DownloadItem> {
    public List<DownloadItem> mDownloadedEpisodeList = new ArrayList<DownloadItem>();
    public boolean CheckBoxVisible = false;
    public SelectionMode SelectMode = SelectionMode.NONE;
    private SparseBooleanArray mSelectedItemsIds;

    public CompletedDownloadAdapter(Context context, int textViewResourceId,
        List<DownloadItem> episodes) {
      super(getActivity(), textViewResourceId, episodes);
      mDownloadedEpisodeList = episodes;
      mSelectedItemsIds = new SparseBooleanArray();
    }

    @Override
    public void remove(DownloadItem object) {
      mDownloadedEpisodeList.remove(object);
      notifyDataSetChanged();
    }

    // public void removeSelection() {
    // mSelectedItemsIds = new SparseBooleanArray();
    // notifyDataSetChanged();
    // }

    public int getSelectedCount() {
      return mSelectedItemsIds.size();
    }

    public SparseBooleanArray getSelectedIds() {
      return mSelectedItemsIds;
    }

    public List<DownloadItem> getRecordings() {
      return mDownloadedEpisodeList;
    }

    public void resetFlag() {
      if (mDownloadedEpisodeList != null) {
        for (DownloadItem item : mDownloadedEpisodeList) {
          item.selected = false;
        }
      }
    }

    @Override
    public int getCount() {
      return mDownloadedEpisodeList.size();
    }

    @Override
    public DownloadItem getItem(int position) {
      return mDownloadedEpisodeList.get(position);
    }

    // public DownloadItem getRecord(int position) {
    // return mDownloadedEpisodeList.get(position);
    // }

    @Override
    public long getItemId(int position) {
      return position;
    }

    private void startOrCancelDownload(DownloadItem episode, String op) {
      // LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
      // LeMachine lm = LeXiaoXiaoBanApp.getInstance().getBaby();

      AlbumItem ai = new AlbumItem();
      ai.id = episode.id;
      ai.url = episode.url;
      ai.album_name = episode.name;
      ai.title = episode.title;
      ai.album_cover = episode.pic;

      if (mStoryType == 0) {

      //  if (mImHelper != null && mImHelper.isLogin()) {
          try {
            JSONObject dataJson = new JSONObject();
            dataJson.put("code", 202);
            dataJson.put("act", "ctldownload");

            JSONObject dataJson22 = new JSONObject();
            dataJson22.put("op", "download");
            dataJson22.put("id", ai.id);
            dataJson22.put("url", ai.url);
            dataJson22.put("name", ai.album_name);
            dataJson22.put("title", ai.title);
            dataJson22.put("attribute", "cartoon");
            dataJson22.put("downloadact", "start");
            dataJson22.put("pic", ai.album_cover);

            dataJson.put("data", dataJson22);
            SocketThreadManager.getInstance().send(dataJson.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
        //}

      } else {

   //     if (mImHelper != null && mImHelper.isLogin()) {
          try {
            JSONObject dataJson = new JSONObject();
            dataJson.put("code", 202);
            dataJson.put("act", "ctldownload");

            JSONObject dataJson22 = new JSONObject();
            dataJson22.put("op", "download");
            dataJson22.put("id", ai.id);
            dataJson22.put("url", ai.url);
            dataJson22.put("name", ai.album_name);
            dataJson22.put("title", ai.title);
            dataJson22.put("attribute", "radio");
            dataJson22.put("downloadact", "start");
            dataJson22.put("pic", ai.album_cover);

            dataJson.put("data", dataJson22);
            SocketThreadManager.getInstance().send(dataJson.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
      //  }
      }

    }

    @SuppressWarnings("deprecation")
    private void updateWidgetFinishDownload(DownloadedViewHolder holder) {
      holder.tv_downloadtime.setTextColor(0xff2bacfc);
      holder.tv_downloadtime.setText("下载完成");

      Drawable db0 = getResources()
          .getDrawable(R.drawable.download_finish_icon);
      holder.tv_download.setCompoundDrawablesWithIntrinsicBounds(null, db0,
          null, null);
      holder.tv_download.setText("下载完成");
      holder.tv_download.setVisibility(View.VISIBLE);
      holder.tv_percent.setVisibility(View.GONE);
      holder.downloadprogress.setVisibility(View.GONE);
      holder.view_root.setVisibility(View.GONE);
      notifyDataSetChanged();
    }

    @SuppressWarnings("deprecation")
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
      final int currentPosition = position;
      final DownloadedViewHolder holder;
      if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(R.layout.listitem_download, parent,
            false);

        holder = new DownloadedViewHolder();
        holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
        holder.Thumbnail = (ImageView) convertView
            .findViewById(R.id.episodeThumbnailView);
        holder.Thumbnail2 = (ImageView) convertView
            .findViewById(R.id.episodeThumbnailView2);
        holder.tv_downloadtime = (TextView) convertView
            .findViewById(R.id.tv_downloadtime);
        holder.tv_percent = (TextView) convertView
            .findViewById(R.id.tv_percent);
        holder.downloadprogress = (ProgressBar) convertView
            .findViewById(R.id.downloadprogress);
        holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
        holder.tv_download = (TextView) convertView
            .findViewById(R.id.tv_download);
        holder.view_root = convertView.findViewById(R.id.view_root);

        holder.SelectedBox = (CheckBox) convertView
            .findViewById(R.id.chooseCheckBox);

        holder.Position = currentPosition;

        holder.SelectedBox
            .setOnCheckedChangeListener(new OnCheckedChangeListener() {

              @Override
              public void onCheckedChanged(CompoundButton buttonView,
                  boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();
                mDownloadedEpisodeList.get(getPosition).selected = buttonView
                    .isChecked();
                if (isChecked) {
                  mSelectedItemsIds.put(currentPosition, isChecked);
                } else {
                  mSelectedItemsIds.delete(currentPosition);
                }
              }
            });

        convertView.setTag(holder);
      } else {
        holder = (DownloadedViewHolder) convertView.getTag();
      }

      holder.SelectedBox.setTag(position);

      holder.downloadprogress.setMax(100);

      if (mStoryType == 0) {
        holder.Thumbnail.setVisibility(View.VISIBLE);
        holder.Thumbnail2.setVisibility(View.GONE);
      } else {
        holder.Thumbnail.setVisibility(View.GONE);
        holder.Thumbnail2.setVisibility(View.VISIBLE);
      }

      try {
        final DownloadItem episode = mDownloadedEpisodeList
            .get(currentPosition);
        holder.tv_title.setText(episode.name);
        holder.tv_name.setText(episode.title);

        // if (mDownloadProgress != null) {
        // if (mDownloadProgress.rsid == episode.id
        // && mDownloadProgress.progress > 0
        // && !episode.downloadstate.contains("FINISHED")
        // && !episode.downloadstate.contains("FAILED")
        // && mDownloadProgress.state != 3 && mDownloadProgress.state != 5) {
        // episode.downloadstate = "DOWNLOADING";
        // }
        // }

        if (mCompletedDownloaded) { // 已下载
          Date d = new Date(episode.dtime);
          holder.tv_downloadtime.setText("下载时间: " + sdf.format(d));
          holder.tv_downloadtime.setTextColor(0xffb2b2b2);
        } else { // 未完成
          holder.tv_downloadtime.setTextColor(getResources().getColor(
              R.color.download_failed_color));
          switch (episode.downloadstate) {
          case "INITIALIZE":
            holder.tv_downloadtime.setTextColor(0xff888888);
            holder.tv_downloadtime.setText("等待中");

            Drawable db00 = getResources().getDrawable(
                R.drawable.delete_download_icon);
            holder.tv_download.setCompoundDrawablesWithIntrinsicBounds(null,
                db00, null, null);

            holder.downloadprogress.setVisibility(View.GONE);
            holder.tv_percent.setVisibility(View.GONE);
            holder.tv_download.setText("删除下载");
            holder.tv_download.setVisibility(View.VISIBLE);
            holder.tv_download.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                startOrCancelDownload(episode, "cancel");

                // holder.view_root.setVisibility(View.GONE);

                if (position < mDownloadedEpisodeList.size()) {
                  mDownloadedEpisodeList.remove(position);// 选择行的位置
                  notifyDataSetChanged();
                }

                // notifyDataSetChanged();
              }
            });

            break;
          case "FINISHED":
            // holder.view_root.setVisibility(View.GONE);
            // if (!mCompletedDownloaded
            // && position < mDownloadedEpisodeList.size()) {
            // mDownloadedEpisodeList.remove(position);// 选择行的位置
            // notifyDataSetChanged();
            // }
            holder.view_root.setVisibility(View.GONE);

            updateWidgetFinishDownload(holder);

            // notifyDataSetChanged();
            break;
          case "DOWNLOADING":
            holder.tv_downloadtime.setTextColor(0xff2bacfc);
            holder.tv_downloadtime.setText("下载中");

            holder.downloadprogress.setVisibility(View.VISIBLE);
            holder.tv_percent.setVisibility(View.VISIBLE);

            Drawable db1 = getResources().getDrawable(
                R.drawable.delete_download_icon);
            holder.tv_download.setCompoundDrawablesWithIntrinsicBounds(null,
                db1, null, null);

            holder.tv_download.setText("删除下载");
            holder.tv_download.setVisibility(View.VISIBLE);

            holder.tv_percent.setText(episode.progress + "%");

            if (mDownProgress != null && mDownProgress.rsid == episode.id
                && mDownProgress.state != 3 && mDownProgress.state != 5) {
              holder.downloadprogress.setProgress(mDownProgress.progress);
              holder.tv_percent.setText(mDownProgress.progress + "%");

              if (mDownProgress.progress == 100) {
                holder.tv_downloadtime.setText("下载完成");

                // if (position < mDownloadedEpisodeList.size()) {
                // mDownloadedEpisodeList.remove(position);// 选择行的位置
                // notifyDataSetChanged();
                // }
              }
            } else {
              holder.downloadprogress.setProgress(episode.progress);
              holder.tv_percent.setText(episode.progress + "%");
              if (mDownProgress.progress == 100) {
                holder.tv_downloadtime.setText("下载完成");

                // if (position < mDownloadedEpisodeList.size()) {
                // mDownloadedEpisodeList.remove(position);// 选择行的位置
                // notifyDataSetChanged();
                // }
              }
            }

            holder.tv_download.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                startOrCancelDownload(episode, "cancel");
                // holder.view_root.setVisibility(View.GONE);

                if (position < mDownloadedEpisodeList.size()) {
                  mDownloadedEpisodeList.remove(position);// 选择行的位置
                  notifyDataSetChanged();
                }

              }
            });

            break;
          case "FAILED":
            holder.tv_downloadtime.setText("下载失败");

            Drawable db2 = getResources().getDrawable(
                R.drawable.download_again_icon);
            holder.tv_download.setCompoundDrawablesWithIntrinsicBounds(null,
                db2, null, null);
            holder.tv_download.setText("重新下载");
            holder.tv_download.setVisibility(View.VISIBLE);
            holder.tv_download.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                startOrCancelDownload(episode, "start");
                episode.downloadstate = "INITIALIZE";
                notifyDataSetChanged();
              }
            });
            holder.tv_percent.setVisibility(View.GONE);
            holder.downloadprogress.setVisibility(View.GONE);
            if (mStoryType == 0) {
              holder.Thumbnail.setColorFilter(new ColorMatrixColorFilter(
                  BT_SELECTED));
            } else {
              holder.Thumbnail2.setColorFilter(new ColorMatrixColorFilter(
                  BT_SELECTED));
            }

            break;
          }
        }

        if (mStoryType == 0) {
          holder.Thumbnail.setTag(position);
          Picasso.with(getActivity()).load(episode.pic).into(holder.Thumbnail);
        } else {
          holder.Thumbnail2.setTag(position);
          Picasso.with(getActivity()).load(episode.pic).into(holder.Thumbnail2);
        }

      } catch (Exception e) {
        e.printStackTrace();
      }

      if (CheckBoxVisible) {
        holder.SelectedBox.setVisibility(View.VISIBLE);
        if (SelectMode == SelectionMode.SELECT_ALL) {
          holder.SelectedBox.setChecked(true);
          setValueForEach(true);
        } else if (SelectMode == SelectionMode.DESELECT_ALL) {
          holder.SelectedBox.setChecked(false);
          setValueForEach(false);
        }
      } else {
        holder.SelectedBox.setVisibility(View.GONE);
      }

      return convertView;
    }

    private void setValueForEach(boolean selected) {
      if (mSelectedItemsIds == null)
        return;
      int i = 0;
      int size = getCount();
      for (; i < size; i++) {
        if (selected)
          mSelectedItemsIds.put(i, selected);
        else
          mSelectedItemsIds.delete(i);
      }
    }

    public void activateSelectMode(boolean activate) {
      this.CheckBoxVisible = activate;
      notifyDataSetChanged();
    }

    public void setSelectionMode(SelectionMode mode) {
      SelectMode = mode;
      notifyDataSetChanged();
    }

  }

  public static CompleteDownloadFragment newInstance(boolean completed,
                                                     int stotyType, BaseActivity ba) {

    CompleteDownloadFragment f = new CompleteDownloadFragment(ba);
    Bundle b = new Bundle();
    b.putBoolean("msg", completed);
    b.putInt("StoryType", stotyType);
    f.setArguments(b);

    return f;
  }

  // @Override
  // public void onDownloadList(final DownloadStateModel data) {
  // getActivity().runOnUiThread(new Runnable() {
  // @Override
  // public void run() {
  // if (mCompletedDownloaded) {
  // if (mStoryType == 0 && data.attribute.contains("cartoon")) {
  // fillList(data);
  // } else if (mStoryType == 1 && data.attribute.contains("radio")) {
  // fillList(data);
  // }
  // } else {
  // if (mStoryType == 0 && data.attribute.contains("cartoon")) {
  // fillList(data);
  // } else if (mStoryType == 1 && data.attribute.contains("radio")) {
  // fillList(data);
  // }
  // }
  // }
  // });
  // }

  private void fillList(DownloadStateModel data) {

    if (mActivity != null) {
      mActivity.dismissLoading();
    }

    if (data == null || data.list == null || data.list.isEmpty()) {
      if (OP_TYPE == AutoListView.REFRESH) {
        mCompletedListView.onRefreshComplete();
        mEpisodeList.clear();
      } else {
        mCompletedListView.onLoadComplete();
      }

      mCompletedListView.setResultSize(0);

      mCompletedListView.setAdapter(mCompletedDownloadAdapter);
      mCompletedListView.setEmptyView(emptyview);
      mCompletedDownloadAdapter.notifyDataSetChanged();
      return;
    }

    if (OP_TYPE == AutoListView.REFRESH) {
      mCompletedListView.onRefreshComplete();
      mEpisodeList.clear();
      mEpisodeList.addAll(data.list);
    } else {
      mCompletedListView.onLoadComplete();
      mEpisodeList.addAll(data.list);
    }

    mCompletedListView.setResultSize(data.list.size());
    mCompletedListView.setAdapter(mCompletedDownloadAdapter);
    mCompletedListView.setEmptyView(emptyview);
    mCompletedDownloadAdapter.notifyDataSetChanged();
  }

  public void activateSelectMode(boolean mVisible) {
    mCompletedDownloadAdapter.activateSelectMode(mVisible);
  }

  public void setSelectionMode(SelectionMode mode) {
    mCompletedDownloadAdapter.setSelectionMode(mode);
  }

  public SparseBooleanArray getSelectedIds() {
    return mCompletedDownloadAdapter.getSelectedIds();
  }

  private class DownloadedViewHolder extends BaseViewHolder {
    public TextView tv_title;
    public TextView tv_name;
    public TextView tv_downloadtime;
    public TextView tv_percent;
    public ProgressBar downloadprogress;
    public TextView tv_download;
    public CheckBox SelectedBox;
    public View view_root; // workaround：下载完毕直接隐藏，删除model总报错
  }

  @Override
  public void onDestroyView() {
//    if (mImHelper != null) {
      SocketThreadManager.getInstance().removeDataReceivedListener(this);
  //  }

    super.onDestroyView();
  }

  @Override
  public void onLoad() {
    handleDownloadAccordType(AutoListView.LOAD);
  }

  @Override
  public void onRefresh() {
    handleDownloadAccordType(AutoListView.REFRESH);
  }

  @Override
  public void onDataReceived(final String recvData) {

    getActivity().runOnUiThread(new Runnable() {
      @Override
      public void run() {
        if (mActivity != null) {
          mActivity.dismissLoading();
        }

        try {
          JSONObject jsonData = new JSONObject(recvData.toString());
          String retcodeStr = null, actStr = null;
          if (jsonData != null && !jsonData.isNull("code")) {
            retcodeStr = jsonData.getString("code");
          }

          if (jsonData != null && !jsonData.isNull("act")) {
            actStr = jsonData.getString("act");
          }

          // 下载列表
          if (Tools.isNotEmpty(retcodeStr) && Tools.isNotEmpty(actStr)
                  && retcodeStr.contains("device")
                  && actStr.contains("getdownloadlist") && jsonData.has("data")) {
            String jsonObjectStr = jsonData.getString("data");
            if (Tools.isNotEmpty(jsonObjectStr)) {
              DownloadStateModel data = JsonSerializer.getInstance().deserialize(
                      jsonObjectStr.toString(), DownloadStateModel.class);

              if (data != null) {
                if (mCompletedDownloaded) {
                  if (mStoryType == 0 && data.attribute.contains("cartoon")) {
                    fillList(data);
                  } else if (mStoryType == 1 && data.attribute.contains("radio")) {
                    fillList(data);
                  }
                } else {
                  if (mStoryType == 0 && data.attribute.contains("cartoon")) {
                    fillList(data);
                  } else if (mStoryType == 1 && data.attribute.contains("radio")) {
                    fillList(data);
                  }
                }
              }
            }
          }

          // 设备上、下线
          if (Tools.isNotEmpty(actStr) && actStr.contains("Device_Login")) {
            LeConfig.isDeviceConnect = true;
          } else if (Tools.isNotEmpty(actStr) && actStr.contains("Device_Logout")) {
            LeConfig.isDeviceConnect = false;
          } else if (Tools.isNotEmpty(actStr)
                  && actStr.contains("Device_APP_Connection_Switched")) { // 被其它账号踢出
            // Jump to Login page
            // Intent logoutIntent = new
            // Intent("com.jdy.haoduoai.activity.logout");
            // getActivity().sendBroadcast(logoutIntent);
            //
            // LeConfig.isLogin = false;
            // LeConfig.isDeviceActivated = false;
            // LeConfig.isDeviceBinded = false;
            // LeConfig.isInfoFilled = false;
            // LeConfig.isDeviceConnect = false;
            //
            // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
            // getActivity()).setTitle("下线通知")
            // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
            // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            //
            // @Override
            // public void onClick(DialogInterface dialog, int which) {
            // dialog.dismiss();
            // }
            // });
            // final CustomOneBtnDialog cd = cdb.create();
            // cd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            // cd.setOnDismissListener(new OnDismissListener() {
            //
            // @Override
            // public void onDismiss(DialogInterface dialog) {
            // Intent toActivityIntent = new Intent(getActivity(),
            // LoginActivity.class);
            // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
            // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(toActivityIntent);
            // getActivity().finish();
            // }
            // });
            //
            // cd.show();
          } else if (Tools.isNotEmpty(actStr) && actStr.contains("downloadstate")) { // 下载状态
            if (!jsonData.isNull("data")) {

              mDownProgress = JsonSerializer.getInstance()
                      .deserialize(jsonData.getJSONObject("data").toString(),
                              DownloadProgress.class);

              // mDownloadResId = jsonData.getJSONObject("data").getInt("rsid");
              if (mCompletedDownloadAdapter != null) {
                mCompletedDownloadAdapter.notifyDataSetChanged();
              }
            }
          }

        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
    });


  }

  DownloadProgress mDownProgress;

}